import axios from 'axios';
import { useAuthStore } from '@/stores/auth';
import { useRouter } from 'vue-router';

const service = axios.create({
    baseURL: 'http://127.0.0.1:5000',
    timeout: 10000
});

// 请求拦截器
service.interceptors.request.use(async (config) => {
    const authStore = useAuthStore();
    if (authStore.token) {
        config.headers.Authorization = `Bearer ${authStore.token}`;
    }
    return config;
});

// 响应拦截器
service.interceptors.response.use(
    response => response,
    error => {
        const authStore = useAuthStore();
        const router = useRouter();
        if (error.response?.status === 401) {
            authStore.clearToken();
            router.replace('/login');
        }
        return Promise.reject(error);
    }
);

export default service;